package com.example.zuulserver1060.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 温伟雄
 * @Date: 2021/10/13/10:54
 * @Description:
 */
@Component
public class LoginCheckFilter extends ZuulFilter {

    private static final Logger log = LoggerFactory.getLogger(LoginCheckFilter.class);

    //执行顺序
    private static final int ORDER=1;

    //filter类型：“pre”前置
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;//pre
    }

    //执行顺序
    @Override
    public int filterOrder() {
        return ORDER;
    }

    //返回结果决定是否要执行run方法
    @Override
    public boolean shouldFilter() {
        // /static/**  ，/login , /register 不需要做登录检查，返回false
        //1、获取request对象，获取请求中的url
        HttpServletRequest request= RequestContext.getCurrentContext().getRequest();
        String url=request.getRequestURI();
        log.info("请求地址："+url);
        //2、判断是否包含 static/**,/login,/registerd的请求
        if(url.endsWith("/login ") || url.endsWith("/register ") || url.contains("/static/") ){
            return false;
        }
        //要做登录检查的返回true
        return true;
    }

    //核心业务方法：登录检查，如果请求头中有token，就是登录成功
    @Override
    public Object run() throws ZuulException {
        //1、获取请求对象
        HttpServletRequest request=RequestContext.getCurrentContext().getRequest();
        //响应对象
        HttpServletResponse response=RequestContext.getCurrentContext().getResponse();

        String token=request.getHeader("token");
        //2、如果没有token，登录检查失败
        if(!StringUtils.hasLength(token)){
            //3.1 返回登录失败的错误信息::{ success:false, message:"登录检查失败，请重新登录"}
            Map<String,Object> resultMap=new HashMap<>();
            resultMap.put("success",false);
            resultMap.put("message","登录检查失败，请重新登录");
            //中文编码
            response.setContentType("application/json;charset=utf-8");
            //把map转成json字符串，写到浏览器中
            String resultJsonString=JSON.toJSONString(resultMap);
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            try {
                response.getWriter().println(resultJsonString);
            } catch (IOException e) {
                e.printStackTrace();
            }
            //3.2 阻止filter继续往后执行
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        //这里的返回结果无任何意义，不用管
        return null;
    }

}
